import { roleListApi, userCreateApi, userDetailUserIdApi, userUpdateApi } from '@/apis/payment'
import { BasicModal, BasicModalProps } from '@/components/BasicModal'
import useMessage from '@/hooks/useMessage'
import { ProFormSelect, ProFormSwitch, ProFormText } from '@ant-design/pro-components'
import { useRequest } from 'ahooks'
import { Form } from 'antd'
import { set, unset } from 'lodash-es'
import { useEffect, useState } from 'react'

export default function AddUserModal({ register, onFinished }: BasicModalProps) {
  const [form] = Form.useForm()
  const { message } = useMessage()
  const [title, setTitle] = useState<string>()
  const { visible, initialValues, onClose } = register()

  const { loading, data: userDetail } = useRequest(getUserDetail, {
    refreshDeps: [visible, initialValues]
  })

  const isEditModal = !!initialValues?.userId

  useEffect(() => {
    if (visible) {
      setTitle(initialValues ? '编辑用户' : '新增用户')
    }
  }, [initialValues, visible, form])

  useEffect(() => {
    form.setFieldsValue(userDetail)
  }, [userDetail, form])

  async function getUserDetail() {
    if (!visible) return
    const userId = initialValues?.userId
    if (!userId) return
    const { success, data } = await userDetailUserIdApi({ userId })
    if (success) {
      return data
    }
  }

  async function getRoleList() {
    const { success, data } = await roleListApi({ rolePage: { pageNum: 1, pageSize: 999 } })
    return success ? data : []
  }

  async function onModalFinished() {
    const values = await form.validateFields()
    unset(values, 'repeatPassword')
    set(values, 'status', values?.status ? 1 : 0)
    const { success } = initialValues?.userId
      ? await userUpdateApi({ ...values, userId: initialValues?.userId })
      : await userCreateApi(values)

    if (success) {
      message.success(initialValues ? '编辑成功' : '新增成功')
      onFinished?.()
      onClose?.()
    }
  }

  return (
    <BasicModal
      title={title}
      width={500}
      form={form}
      loading={loading}
      labelCol={{ span: 4 }}
      layout="horizontal"
      register={register}
      onFinish={onModalFinished}
    >
      <ProFormText
        name="username"
        label="用户名称"
        rules={[{ required: true, message: '请输入用户名称' }]}
      />
      <ProFormText
        name="realName"
        label="用户姓名"
        rules={[{ required: true, message: '请输入用户姓名' }]}
      />
      {!isEditModal && (
        <ProFormText.Password
          name="password"
          label="密码"
          hidden={isEditModal}
          rules={[{ required: true, message: '密码不能为空' }]}
        />
      )}
      {!isEditModal && (
        <ProFormText.Password
          name="repeatPassword"
          label="重复密码"
          rules={[
            { required: true, message: '重复密码不能为空' },
            ({ getFieldValue }) => ({
              validator: (_, value) => {
                if (value !== getFieldValue('password')) {
                  return Promise.reject('两次输入密码不一致')
                }
                return Promise.resolve()
              }
            })
          ]}
        />
      )}

      <ProFormSelect
        name="roleIds"
        label="角色权限"
        request={getRoleList}
        fieldProps={{ fieldNames: { label: 'roleName', value: 'roleId' }, mode: 'multiple' }}
      />
      <ProFormSwitch
        name="status"
        label="用户状态"
        initialValue={true}
        fieldProps={{
          checkedChildren: '启用',
          unCheckedChildren: '禁用'
        }}
        rules={[{ required: true, message: '请选择状态' }]}
      />
    </BasicModal>
  )
}
